﻿using Ecommerce;
using Ecommerce.DTO;
using Ecommerce.tbCommodity;
using Hangfire;
using Microsoft.Extensions.Hosting;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;

namespace LiveShopvnext.Hangfire
{
    public class HangfireService : BackgroundService
    {
        private readonly IRepository<tbOrderInfo, Guid> _tbOrderInfos;
        private readonly IRepository<tbSaleNum, Guid> _tbSaleNums;
        private readonly IRepository<tbCommodityInfo, Guid> _tbCommodityInfos;
        private readonly OrderService _orderInfoService;
        public HangfireService(IRepository<tbCommodityInfo, Guid> tbCommodityInfos, IRepository<tbSaleNum, Guid> tbSaleNums, IRepository<tbOrderInfo, Guid> tbOrderInfos, OrderService orderInfoService) 
        {
            _tbCommodityInfos = tbCommodityInfos;
            _tbOrderInfos = tbOrderInfos;
            _tbSaleNums = tbSaleNums;
            _orderInfoService = orderInfoService;
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //任务每分钟执行一次
            RecurringJob.AddOrUpdate(() => HangfireJob(), Cron.Minutely());
            return Task.CompletedTask;
        }

        public async Task HangfireJob()
        {
            var list = await _orderInfoService.GetOrderInfos();
            for (int i = 0; i <list.Count() ; i++)
            {
                foreach (var item in _tbOrderInfos.ToList().Where(s => s.OrderInfoAuditState == 10 || s.OrderInfoState == 10))
                {
                    item.CreationTime = item.CreationTime.AddDays(1);
                    if (item.CreationTime >= DateTime.Now)
                    {
                        var lists = _tbOrderInfos.Where(o => o.Id.ToString().Equals(item.Id.ToString())).FirstOrDefault();//获取到该订单信息表的的信息
                        lists.OrderInfoAuditState = 20;//审核状态  20已取消
                        lists.OrderInfoState = 50;//订单状态    50取消订单
                        var info = _tbSaleNums.Where(s => s.OrderInfoId.Equals(item.Id.ToString())).ToList();//查询到当前订单下面的商品信息
                        foreach (var items in info)//进行循环
                        {
                            var commodity = _tbCommodityInfos.Where(s => s.Id.ToString().Equals(items.CommodityId)).FirstOrDefault();//通过订单表中的商品Id查询出该商品的信息
                            commodity.CommoidtyNum = commodity.CommoidtyNum + items.Num;//将数量加上购买数量
                            await _tbCommodityInfos.UpdateAsync(commodity);//保存数据库
                        }
                        await _tbOrderInfos.UpdateAsync(lists);//保存数据库
                    }
                }
            }

            //var info = new tbOrderInfo() { CommodCountPrice = 1 };
            //_tbOrderInfos.InsertAsync(info);

        }
    }
}
